package kr.kwakyc.puzzle.ranking;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class RankingDatabaseFromFile implements RankingDatabase {
	
	private String fileName = "record.txt";
	
	@Override
	public List<RankingRecord> list() {
		List<RankingRecord> rankingRecords = new ArrayList<RankingRecord>();
		
		try{
			BufferedReader br = new BufferedReader(new FileReader(fileName));
			
			String line;
			
			while((line = br.readLine()) != null){
				String[] splitLine = line.split(",");
				
				RankingRecord record = new RankingRecord();
				record.setName(splitLine[0]);
				record.setSecond(Integer.parseInt(splitLine[1]));
				
				rankingRecords.add(record);
			}
			
			br.close();
		}catch(Exception e){
		}
		
		return rankingRecords;
	}

	@Override
	public void insert(RankingRecord record) {
		try {
			PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(fileName, true)));
			pw.println(record.getName() + "," + record.getSecond());
			pw.close();
		} catch (Exception e) {
		}
		
	}

}
